import React, { FC, useEffect, useState, useRef, useMemo } from "react";
// import {useSearchParams} from  'react-router-dom'
import QuestionCard from "../../components/QuestionCard";
import ListSearch from "../../components/ListSearch";
import styles from "./common.module.scss";
import { useTitle, useRequest, useDebounceFn } from "ahooks";
import { Typography, Spin, Empty } from "antd";
import { getQuestionListService } from "../../services/question";
import { useSearchParams } from "react-router-dom";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../constant/index";
const { Title } = Typography;

const List: FC = () => {
  useTitle("小叶问卷 - 我的问卷");
  const [SearchParams] = useSearchParams();

  const [started, setStarted] = useState(false); //是否已经开始加载，因为防抖有延迟时间
  const [page, setPage] = useState(1);
  const [list, setList] = useState([]); //全部的列表数据
  const [total, setTotal] = useState(0);
  const haveMoreData = total > list.length;
  const keyword = SearchParams.get(LIST_SEARCH_PARAM_KEY) || "";

  //keyword变化时重置信息
  useEffect(() => {
    setStarted(false);
    setPage(1);
    setList([]);
    setTotal(0);
  }, [keyword]);

  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        keyword,
        page,
        pageSize: LIST_PAGE_SIZE,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: l = [], total = 0 } = result;
        setList(list.concat(l)); //累计
        setTotal(total);
        setPage(page + 1);
      },
    }
  );

  const containerRef = useRef<HTMLDivElement>(null);
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = containerRef.current;
      if (elem == null) return;
      const domRect = elem.getBoundingClientRect();
      if (domRect == null) return;
      const { bottom } = domRect;
      if (bottom <= document.body.clientHeight) {
        load();
        setStarted(true);
      }
    },
    {
      wait: 1000,
    }
  );

  useEffect(() => {
    tryLoadMore();
  }, [SearchParams]);

  // 当页面滚动时，尝试触发加载
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
      //防抖
    }
    return () => {
      window.removeEventListener("scroll", tryLoadMore);
    };
  }, [SearchParams, haveMoreData]);

  // loadMore Elem
  const LoadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin />;
    if (total === 0) return <Empty description="暂无数据" />;
    if (!haveMoreData) return <span>没有更多数据了...</span>;

    return <span>loading more</span>;
  }, [started, loading, haveMoreData]);

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {list.length > 0 &&
          list.map((q: any) => {
            const { _id } = q;
            return <QuestionCard key={_id} {...q} />;
          })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>{LoadMoreContentElem }</div>
      </div>
    </>
  );
};

export default List;
